package com.example.venue_reservation_service.mq;

import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

@Service
public class DelayMessageSender {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    // 发送预约检查延迟消息
    public void sendReservationCheck(long reservationId, LocalDate reservationDate, LocalTime end) {
        // 计算延迟时间（毫秒）
        long delayMills = calculateDelay(reservationDate, end);

        // 发送延迟消息
        sendDelayedMessage("delay.routing.key", reservationId, delayMills);
    }

    // 发送15秒延迟的测试消息
    public void sendTestMessage() {
        System.out.println("[" + LocalTime.now() + "] 发送测试消息，将在15秒后消费");
        sendDelayedMessage("delay.routing.key", "TEST_MESSAGE", 15000);
    }

    private long calculateDelay(LocalDate date, LocalTime time) {
        LocalDateTime target = LocalDateTime.of(date, time);
        long targetMills = target.toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
        long currentMills = System.currentTimeMillis();
        return Math.max(0, targetMills - currentMills);
    }

    private void sendDelayedMessage(String routingKey, Object message, long delayMillis) {
        rabbitTemplate.convertAndSend("delayed.exchange", routingKey, message, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                // 设置延迟时间（毫秒）
                message.getMessageProperties().setHeader("x-delay", delayMillis);
                return message;
            }
        });
    }
}